package com.dongdongshop.controller;

import com.dongdongshop.constant.HttpResultEnum;
import com.dongdongshop.data.DataResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * @Author Eayon
 * @Date 2020/2/27 9:49
 */
@Controller
@RequestMapping("login")
public class LoginController {

    private Logger log = LoggerFactory.getLogger(LoginController.class);

    /**
     * 跳转商家后台登录页
     * @return
     */
    @RequestMapping("toLogin")
    public String toLogin(){
        return "shoplogin";
    }

    /**
     * 登录校验方法
     * @param sellerId
     * @param password
     * @return
     */
    @RequestMapping("loginCheck")
    public String loginCheck(String sellerId, String password, Model model){
        try {
            //1、获取subject  Subject:用户主题
            Subject subject = SecurityUtils.getSubject();
            //2、将用户的账号密码封装到token中
            UsernamePasswordToken token = new UsernamePasswordToken(sellerId,password);
            subject.login(token);
            //跳转商家后台管理首页
            return "redirect:/login/toIndex";
        }catch (UnknownAccountException  e){//账号不存在报这个错
            log.error("登录校验异常账号不存在",e);
            model.addAttribute("message","账号不存在");
            return "shoplogin";
        }catch (IncorrectCredentialsException e){//密码不正确报这个错
            log.warn("登录校验异常密码错误",e);
            model.addAttribute("message","密码错误");
            return "shoplogin";
        }

    }

    /**
     * 跳转商家后台管理首页
     * @return
     */
    @RequestMapping("toIndex")
    public String toIndex(){
        return "admin/index";
    }


    /**
     * 跳转商家注册页
     * @return
     */
    @RequestMapping("toRegister")
    public String toRegister(){
        return "register";
    }

    /**
     * 跳转商家入驻协议详情页
     * @return
     */
    @RequestMapping("toSampling")
    public String toSampling(){
        return "sampling";
    }
}
